const express = require('express');
const fs = require('fs');
const path = require('path');

const methods = require('./03-methods')

const router = express.Router();

const data = require('./data.json');

const dbpath = path.join(__dirname, 'data.json')
router
  .get('/',(req,res) => {
    res.render('index.html',{
      list:data.students
    })
  })

  // 添加学生
  .get('/add',(req,res) => {
    res.render('add.html')
  })
  .post('/add',(req,res) => {
    const body = req.body
    methods.add(body,err => methods.find(err,res))
  })

  // 修改学生
  .get('/edit',(req,res) => {
    res.render('edit.html',{
      message: data.students.find(item => item.id === parseInt(req.query.id))
    })
  })
  .post('/edit',(req,res) => {
    var body = req.body
    methods.edit(body,err => methods.find(err,res))
  })

  // 删除学生
  .get('/delete',(req,res) => {
    // res.setHeader('Access-Control-Alow-Methods','DELETE')
    methods.delete(req.query,err => methods.find(err,res))
  })
  
module.exports = router